<template>
  <div class="wrap wrap_order_detail">
    <div class="mod_order_header">
      <img src="/static/img/order_bg_pic.png" alt="" class="bg_pic">
      <div class="iconfont"
          :class="{'icon-zsclock': showPay,
                   'icon-zsselected': !showPay && (detail.status === 20 || detail.status === 40 || detail.status === 50),
                   'icon-zswarning': !showPay && (detail.status !== 20 && detail.status !== 40 && detail.status !== 50)}">
      </div>
      <div class="title">{{detail._sName}}！</div>
      <div class="desc">订单号：{{orderId}}</div>
    </div>
    <div class="mod_order_checkout" :class="{none: !showPay}" v-if="detail.is_appointment != 1">
      <div class="checkout_title">
        剩余支付时间 {{coTime}}
      </div>
      <div class="btn_chekcout" @click="orderBuy">立即支付</div>
    </div>
    <div class="mod_order_count" v-if="detail.is_appointment != 1">
      <div class="count_title">
        订单总额 <span class="price">&yen;{{detail.total_amount}}</span>
      </div>
      <div class="count_cut">
        ¥{{goods.unit_price}}x{{goods.quantity}}
        <span v-if="detail.dis_amount">优惠券 -¥{{ detail.dis_amount }}</span>
      </div>
    </div>

    <div class="mod_refund_progress" v-if="detail.is_refund !== 0 && detail.is_appointment !==1">
      <div class="count_title">
        退款金额 <span class="price">&yen;{{detail.refund_amount}}</span>
      </div>
      <div class="refund_progress">
        <div class="item" :class="{current: detail.status === 30 || detail.status === 31 || detail.status === 32 || detail.status === 40}">
          <div class="num">1</div>
          <div class="text">提交申请</div>
        </div>
        <div class="item" :class="{current: detail.status === 31 || detail.status === 32 || detail.status === 40}">
          <div class="num">2</div>
          <div class="text">商家处理</div>
        </div>
        <div class="item" :class="{current: detail.status === 32 || detail.status === 40}">
          <div class="num">3</div>
          <div class="text">微信支付处理</div>
        </div>
        <div class="item item_4" :class="{current: detail.status === 40}">
          <div class="num">
            <div class="iconfont icon-zsselected"></div>
          </div>
          <div class="text">退款成功</div>
        </div>
      </div>
      <div class="refund_info" :class="{none: detail.status !== 32}">
        退款金额已提至微信支付，微信支付会在1-3个工作日内完成处理。
      </div>
    </div>

    <div class="mod_refund_progress" v-if="detail.is_refund !== 0 && detail.is_appointment ===1">
      <div class="count_title">
        取消预约
      </div>
      <div class="refund_progress">
        <div class="item" :class="{current: detail.status === 30 || detail.status === 31 || detail.status === 32 || detail.status === 40}">
          <div class="num">1</div>
          <div class="text">提交申请</div>
        </div>
        <div class="item" :class="{current: detail.status === 31 || detail.status === 32 || detail.status === 40}">
          <div class="num">2</div>
          <div class="text">商家处理</div>
        </div>
        <div class="item item_4" :class="{current: detail.status === 40}">
          <div class="num">
            <div class="iconfont icon-zsselected"></div>
          </div>
          <div class="text">取消成功</div>
        </div>
      </div>
    </div>

    <div class="mod_box_title">
      <div class="title" @click="gotoDetail(goods)">{{detail.order_title}}</div>
      <div class="order_content" v-if="goods.gt_id !== 3">
        <div class="order_line">
          <div class="lable">出游时间</div>
          <div class="value">
            {{detail._sTime}}
          </div>
        </div>
        <div class="order_line">
          <div class="lable">门票数量</div>
          <div class="value">
            {{detail.quantity}}张
          </div>
        </div>
      </div>
    </div>

    <div class="mod_box" v-if="visitors.length">
      <div class="mod_hd">
        <div class="title">游客</div>
      </div>
      <div class="mod_bd">
        <div class="order_content">
          <div v-for="(item, index) in visitors" :key="item.v_id">
            <div class="order_line">
              <div class="lable">游客{{index + 1}}</div>
              <div class="value">
                {{item.v_truename}}
              </div>
            </div>
            <div class="order_line">
              <div class="lable">身份证</div>
              <div class="value">
                {{item.v_id_card}}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mod_box" v-if="detail.contact_tel">
      <div class="mod_hd">
        <div class="title">联系人</div>
      </div>
      <div class="mod_bd">
        <div class="order_content">
          <div class="order_line">
            <div class="lable">手机号</div>
            <div class="value">
              {{detail.contact_tel}}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mod_box" v-if="detail.status === 20 || (detail.is_appointment == 1 && detail.status === 50)">
      <div class="mod_bd">
        <div class="mod_qr_area">
          <div class="qr_title" :class="{none: !showQRCode}">
            <img src="/static/img/me_tuijian_title_left.png" alt="" class="d1">
            <div class="title">扫下方二维码入园</div>
            <img src="/static/img/me_tuijian_title_right.png" alt="" class="d2">
          </div>

          <img class="qr_pic" :src="detail.qr_code" alt="" v-if="showQRCode" />
          <div class="gap" style="height:15px" v-if="!showQRCode"></div>

          <div class="btn_grey" :class="{none: detail.is_refund === 1}" @click="doRefund" v-if="detail.is_appointment != 1">申请退款</div>

          <div class="btn_grey" @click="doRefund" v-if="detail.is_appointment == 1 &&  detail.is_refund === 0">取消预约</div>
        </div>
      </div>
    </div>

    <div class="mod_box mod_box_coupon" :class="{none: coupons.length === 0}">
      <div class="mod_hd">
        <div class="title">优惠券赠送</div>
      </div>
      <div class="mod_bd">
        <div class="coupon_list">
          <a class="coupon_item"
              v-for="item in coupons"
              :key="item.coupon_id">

            <div class="aside">
              <img src="/static/img/bg_yhq.png" alt="" class="coupon_bg">
              <span class="text">&yen;{{item.face_value}}</span>
            </div>
            <div class="content">
              <div class="title">{{item.name}}</div>
              <div class="desc">有效期：至{{item._endtime}}</div>
              <div class="btn_em orange" @click="getCoupon(item.coupon_id)">领取</div>
              <div class="iconfont icon-zsinto"></div>
            </div>
          </a>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import fly from '@/utils/fly'
import { getOpenid } from '@/utils/login'
import { STATUS_DICT, doPay } from '@/utils/order'
import { formatTime } from '@/utils/index'
import { reportData } from '@/utils/report'
let cInterval

export default {
  data () {
    return {
      orderId: '',
      goods: {},
      detail: {},
      visitors: [],
      coupons: [],
      showPay: false,
      coTime: '',
      showQRCode: false
    }
  },
  methods: {
    doRefund () {
      wx.navigateTo({
        url: '/pages/refund/main?id=' + this.orderId
      })
    },
    async getCouponList () {
      let openid = await getOpenid()
      let res = await fly.post(`Coupon/list?wx_openid=${openid}&include_goods=${this.goods.goods_id}`)
      if (res && res.code === 200 && res.data) {
        res.data.list.forEach(item => {
          item._endtime = formatTime(new Date(item.end_time * 1000)).slice(0, 10)
        })
        this.coupons = res.data.list
      }
    },
    async getCoupon (id) {
      let openid = await getOpenid()
      let res = await fly.post(`Coupon/get?wx_openid=${openid}&coupon_id=${id}`)
      if (res && res.code === 200 && res.data) {
        wx.showToast({
          title: `领取成功`,
          icon: 'success'
        })
        // 重新拉取一次优惠券列表
        await this.getCouponList()
      } else {
        wx.showToast({
          title: `领取失败${res ? ('(' + res.code + ')') : ''}`,
          icon: 'none'
        })
      }
    },
    async orderBuy () {
      let that = this
      if (that.detail.is_appointment === 1) {
        return
      }
      let wxPayRes = await doPay(this.orderId)
      if (wxPayRes && wxPayRes.code === 200) {
        that.showPay = false
        wx.showLoading({
          title: '加载中'
        })

        clearInterval(cInterval)

        setTimeout(function () {
          wx.hideLoading()
          that.loadData()
        }, 2000)
      } else {

      }
    },
    async loadData () {
      let openid = await getOpenid()
      let res = await fly.post(`Order/details?wx_openid=${openid}&order_sn=${this.orderId}`)
      if (res && res.code === 200 && res.data) {
        let detail = res.data.order
        detail._sName = STATUS_DICT['' + detail.status]
        if (detail.is_appointment === 1) {
          if (detail.status === 20) {
            detail._sName = '预定成功'
          } else if (detail.status === 99) {
            detail._sName = '预定失败'
          } else if (detail.status === 50) {
            detail._sName = '预定完成'
          } else if (detail.status === 30) {
            detail._sName = '取消预定'
          } else if (detail.status === 40) {
            detail._sName = '取消预定成功'
          }
        }
        detail._sTime = (function () {
          let s = new Date(detail.start_time * 1000)
          let e = new Date(detail.end_time * 1000)
          let weekday = new Array(7)
          weekday[0] = '周日'
          weekday[1] = '周一'
          weekday[2] = '周二'
          weekday[3] = '周三'
          weekday[4] = '周四'
          weekday[5] = '周五'
          weekday[6] = '周六'

          if (detail.is_appointment === 1) {
            return `${s.getFullYear()}年${s.getMonth() + 1}月${s.getDate()}日 ${weekday[s.getDay()]} ${s.getHours()}:${e.getMinutes() < 10 ? '0' + e.getMinutes() : e.getMinutes()} - ${e.getHours()}:${e.getMinutes() < 10 ? '0' + e.getMinutes() : e.getMinutes()}`
          } else {
            return `${s.getFullYear()}年${s.getMonth() + 1}月${s.getDate()}日 ${weekday[s.getDay()]}`
          }
        })()

        detail.dis_amount = (detail.dis_amount + '').replace('-', '') - 0

        this.goods = res.data.goods[0]
        this.detail = detail
        this.visitors = res.data.visitors

        // 计算剩余支付时间
        if (detail.status === 10) {
          let that = this
          let cTime = detail.create_time * 1000
          clearInterval(cInterval)
          cInterval = setInterval(function () {
            let nowTime = +new Date()
            let num = Math.round((nowTime - cTime) / 1000)
            let tTime = 1800
            if (num <= tTime && that.detail.status === 10) {
              console.log('showPay----1', that.detail.status)
              that.showPay = true
              that.coTime = `${('0' + Math.floor((tTime - num) / 60)).slice(-2)}:${('0' + (tTime - num) % 60).slice(-2)}`
            } else {
              console.log('showPay----2', that.detail.status)
              that.showPay = false
              clearInterval(cInterval)
            }
          }, 1000)

          reportData({
            funcx: '交易流程-待支付',
            keyx: this.goods.goods_id + '_' + this.orderId
          })
        }
        this.showQRCode = (detail.status === 20 || !!detail.qr_code)

        if (detail.status === 30) {
          // 退款申请已提交
          reportData({
            funcx: '交易流程-退款申请-退款申请已提交',
            keyx: this.goods.goods_id + '_' + this.orderId
          })
        }
        // 拉取优惠券信息
        await this.getCouponList()
      } else {

      }
    },
    gotoDetail (item) {
      if (item.gt_id === 3) {
        wx.navigateTo({
          url: '/pages/detail/main?id=' + (item.r_id || 187)
        })
      } else {
        wx.navigateTo({
          url: '/pages/goods-detail/main?id=' + item.goods_id
        })
      }
    }
  },
  async onLoad () {
    const {
      id
    } = this.$root.$mp.query
    this.orderId = id

    wx.setNavigationBarTitle({
      title: '订单详情'
    })

    await this.loadData()
  },
  onShow () {
    this.loadData()
  }
}
</script>

<style lang="scss">
@import "order-detail.scss";
</style>
